package com.djakapm.markdown.editor.component;

import com.djakapm.markdown.editor.AppConstant;
import com.djakapm.swing.component.EditorPaneView;
import com.djakapm.swing.container.BorderPanel;

import javax.swing.*;
import javax.swing.text.html.HTMLEditorKit;
import java.awt.*;
import java.awt.datatransfer.StringSelection;

public class MarkupView extends BorderPanel {
    private EditorPaneView textEditor;
    private EditorPaneView htmlEditor;
    private JEditorPane htmlComponent;
    private JEditorPane textComponent;
    private JToolBar toolbar = new JToolBar();

    public MarkupView() {
        this.htmlEditor = new EditorPaneView();
        this.htmlComponent = this.htmlEditor.getComponent();

        this.textEditor = new EditorPaneView();
        this.textComponent = this.textEditor.getComponent();

        this.configureTextComponent();
        this.setEnabled(false);
        this.addToNorth(this.toolbar).addToCenter(this.htmlEditor);

    }

    public JToolBar getToolBar() {
        return this.toolbar;
    }
    
    private void configureTextComponent() {
        this.htmlComponent.setEditorKitForContentType(AppConstant.HTML_CONTENT_TYPE, new HTMLEditorKit());
        this.htmlComponent.setContentType(AppConstant.HTML_CONTENT_TYPE);
        this.htmlComponent.setEditable(false);
        
        this.textComponent.setEditable(false);
    }

    private String extractPageContent(String htmlStr) {
        String cleanHTMLStr;
        int begin;
        int end;

        begin = htmlStr.indexOf("<body>");
        end = htmlStr.indexOf("</body>");

        if(begin < 0){return htmlStr;}
        if(end < 0){return htmlStr;}

        cleanHTMLStr = htmlStr.substring(begin + "<body>".length(), end).trim();
        return cleanHTMLStr;
    }

    public MarkupView sourceMode() {
        this.remove(this.htmlEditor);
        this.addToCenter(this.textEditor);
        this.revalidate();
        this.repaint();
        return this;
    }

    public MarkupView renderMode() {
        this.remove(this.textEditor);
        this.addToCenter(this.htmlEditor);
        this.repaintView();
        return this;
    }

    public MarkupView setText(String content) {
        this.htmlEditor.setText(content);
        this.textEditor.setText(content);
        this.repaintView();
        return this;
    }

    public MarkupView copyContentToClipboard(){
        StringSelection ss = new StringSelection(this.extractPageContent(this.htmlComponent.getText()));
        Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, null);

        return this;
    }

    private MarkupView repaintView(){
        this.revalidate();
        this.repaint();
        return this;
    }

}
